package com.example.springmvcdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
public class StaticPageController {

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 使用ResponseEntity返回静态内容
     * 适用于需要动态控制静态内容的场景
     */
    @RequestMapping("/dynamic-static")
    public ResponseEntity<String> dynamicStaticContent() throws IOException {
        // 读取静态文件内容
        Resource resource = resourceLoader.getResource("classpath:static/index.html");
        String content = new String(Files.readAllBytes(Paths.get(resource.getURI())));

        // 使用ResponseEntity返回内容并设置Content-Type
        return ResponseEntity.ok()
                .contentType(MediaType.TEXT_HTML)
                .body(content);
    }



    /**
     * 使用ResponseEntity返回文本数据
     */
    @RequestMapping("/response-entity-text")
    public ResponseEntity<String> returnTextWithResponseEntity() {
        return ResponseEntity.ok()
                .header("Custom-Header", "value")
                .body("ResponseEntity返回的文本数据");
    }
}
